package cn.sundat.web.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import cn.sundat.model.Category;
import cn.sundat.model.News;
import cn.sundat.model.PageBean;
import cn.sundat.service.NewsService;
import cn.sundat.utils.FastJsonUtil;
import cn.sundat.utils.ThumbImgUtils;
import cn.sundat.utils.UploadUtils;

public class AdminNewsAction extends ActionSupport implements ModelDriven<News>{
	private static final long serialVersionUID = 5359206932950201393L;
	//模型驱动封装news
	private News news = new News();
	
	public News getModel() {
		return news;
	}
	
	@Resource(name="newsService")
	private NewsService newsService;
	
	//属性驱动的方式封装当前页
	private Integer currPage=1;
	
	public void setCurrPage(Integer currPage) {
		if(currPage==null) {
			currPage=1;
		}
		this.currPage = currPage;
	}
	
	//属性驱动的方式封装页面显示条目数量
	private Integer pageSize=7;
	
	public void setPageSize(Integer pageSize) {
		if(pageSize==null) {
			pageSize=2;
		}
		this.pageSize = pageSize;
	}
	
	//属性驱动的方式封装类别
	private Long categoryId=3L;

	public void setCategoryId(Long categoryId) {
		if(categoryId==null) {
			categoryId=3L;
		}
		this.categoryId = categoryId;
	}
	
	/**
	 * Struts2的fileuploadinterceptor自己封装数据
	 */
	private File upload;
	private String uploadContentType;
	private String uploadFileName;

	public void setUpload(File upload) {
		this.upload = upload;
	}
	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	/**
	 * 添加一条文章或者新闻
	 * @return
	 * @throws IOException 
	 */
	public String add() throws IOException {
		HttpServletRequest request = ServletActionContext.getRequest();
		String news_isshow = request.getParameter("news_isshow");
		String editorValue = request.getParameter("editorValue");
		
		//封装图片
		if(uploadFileName!=null && !uploadFileName.trim().isEmpty()) {
			//给一个固定的位置存储图片
			String path = ServletActionContext.getServletContext().getRealPath("/upload");
			File file = new File(path);
			if(!file.exists() && !file.isDirectory()) {
				file.mkdir();
			}
			//获取随机名称
			String uuidName = UploadUtils.getUUIDName(uploadFileName);
			
//			File filePath = new File(file,uuidName);
//			FileUtils.copyFile(upload, filePath);
			System.out.println(uploadFileName);
			if(uploadFileName.contains("jpg") || uploadFileName.contains("jpeg")) {
				//图片就生成缩略图
				ThumbImgUtils.slt(upload.getAbsolutePath(), file+File.separator+uuidName);
			}else {
				//直接写到本地
				File newfile = new File(file+File.separator+uuidName);
				FileUtils.copyFile(upload, newfile);
			}
			
			
			//设置参数
			news.setImg("upload/"+uuidName);
		}
		
		//将属性封装到对象
		if(news_isshow==null) {
			news_isshow="0";
		}
		news.setNews_isshow(Integer.parseInt(news_isshow));
		news.setNews_content(editorValue);
		
		//调用service插入到数据库中
		newsService.save(news);
		return SUCCESS;
	}
	
	/**
	 * 根据类别分页查询
	 */
	public String findByPage() {
		//QBC的离线条件查询
		DetachedCriteria criteria = DetachedCriteria.forClass(News.class);
		//拼接查询条件
		Category c = new Category();
		c.setCate_id(categoryId);
		criteria.add(Restrictions.eq("category", c));
		//获取id封装对象的其他属性
		PageBean<News> page = newsService.findByPage(currPage,pageSize,criteria);
		HttpServletResponse response = ServletActionContext.getResponse();
		String jsonString = FastJsonUtil.toJSONString(page.getBeanlist());
		FastJsonUtil.write_json(response, jsonString);
//		ServletActionContext.getRequest().setAttribute("page", page);
//		System.out.println("分页显示的page是"+page.getTotalPage());
		return NONE;
	}
	
	/**
	 * 根据类别查询
	 */
	public String findByCategory() {
		//QBC离线条件查询
		DetachedCriteria criteria = DetachedCriteria.forClass(News.class);
		//拼接查询条件
		Category c = new Category();
		c.setCate_id(categoryId);
		criteria.add(Restrictions.eq("category", c));
		criteria.addOrder(Order.desc("news_id"));
		if(news.getNews_title()!=null && !news.getNews_title().trim().isEmpty()) {
			criteria.add(Restrictions.like("news_title", "%"+news.getNews_title()+"%"));
		}
		
		//调用newsService查询
		List<News> list =  newsService.findByAdminCategory(criteria);
		//将数据转为json格式并写回浏览器
		HttpServletResponse response = ServletActionContext.getResponse();
		String jsonString = FastJsonUtil.toJSONString(list);
		FastJsonUtil.write_json(response, jsonString);
		return NONE;
	}
	
	/**
	 * 删除news
	 * @return
	 */
	public String del() {
		newsService.del(news.getNews_id());
		return NONE;
	}
	
	/**
	 * 编辑news，做一个回显
	 * @return
	 * @throws IOException 
	 */
	public String updateById() throws IOException {
		news =  newsService.findById(news.getNews_id());
		/*String n = FastJsonUtil.toJSONString(news);*/
		ServletActionContext.getRequest().setAttribute("n", news);
		return "editok";
	}
	
	/**
	 * 更新news
	 * @return
	 * @throws IOException 
	 */
	public String edit() throws IOException {
		HttpServletRequest request = ServletActionContext.getRequest();
		String news_isshow = request.getParameter("news_isshow");
		String editorValue = request.getParameter("editorValue");
//		String oldpath = request.getParameter("img");
		//判断是否有图片的上传
		if(uploadFileName!=null) {
			String realPath1 = ServletActionContext.getServletContext().getRealPath("");
			//删除原来图片
			String imgpath = news.getImg();
			if(imgpath!=null && !imgpath.trim().isEmpty()) {
				File file = new File(realPath1+imgpath);
				System.out.println(realPath1+imgpath);
				file.delete();
			}
			//上传新的图片
			String uuidName = UploadUtils.getUUIDName(uploadFileName);
			String realPath = ServletActionContext.getServletContext().getRealPath("/upload");
			File file = new File(realPath);
			if(file.exists()) {
				file.exists();
			}
//			File newFile = new File(file,uuidName);
//			FileUtils.copyFile(upload, newFile);
			ThumbImgUtils.slt(upload.getAbsolutePath(), file+File.separator+uuidName);
			//设置图片新的位置
			news.setImg("upload"+File.separator+uuidName);
			
		}
		//将属性封装到对象
		if(news_isshow==null) {
			news_isshow="0";
		}
		news.setNews_isshow(Integer.parseInt(news_isshow));
		news.setNews_content(editorValue);
		
		//调用service插入到数据库中
		newsService.update(news);
		return SUCCESS;
	}
	
	/**
	 * 修改展示状态
	 * @return
	 */
	public String editState() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String news_isshow = request.getParameter("news_isshow");
		long news_id = Long.parseLong(request.getParameter("news_id"));
		int isshow_num = Integer.parseInt(news_isshow);
		
		//只修改这个记录的state
		News oldNews = newsService.findById(news_id);
		if(isshow_num==1) {
			isshow_num=0;
		}else {
			isshow_num=1;
		}
		oldNews.setNews_isshow(isshow_num);
		newsService.update(oldNews);
		return SUCCESS;
	}
}
